package com.monitor.ui.controller;

import com.monitor.security.RegistrationManager;
import com.monitor.util.SystemInfoUtil;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * 注册对话框控制器，处理系统注册逻辑
 */
public class RegistrationDialogController implements Initializable {

    @FXML
    private TextField registrationCodeField;

    @FXML
    private TextField companyField;
    
    @FXML
    private Spinner<Integer> startGradeSpinner;
    
    @FXML
    private Spinner<Integer> endGradeSpinner;
    
    @FXML
    private ComboBox<DeviceType> deviceTypeCombo;

    @FXML
    private Label gradeLabel;
    
    @FXML
    private javafx.scene.layout.HBox gradeBox;
    
    @FXML
    private Label teacherLabel;
    
    @FXML
    private TextField teacherNameField;
    
    @FXML
    private Label teacherRequiredLabel;

    @FXML
    private TextField emailField;

    @FXML
    private TextField phoneField;

    @FXML
    private ComboBox<String> securityQuestionCombo;

    @FXML
    private TextField securityAnswerField;
    
    @FXML
    private TextField confirmAnswerField;

    @FXML
    private Button cancelButton;

    @FXML
    private Button registerButton;

    @FXML
    private Label statusLabel;

    private RegistrationManager registrationManager;
    private Stage primaryStage;
    
    /**
     * 设备类型枚举
     */
    public enum DeviceType {
        ALL_IN_ONE(0, "一体机"),
        COMPUTER_ROOM(1, "机房设备"),
        TEACHER_DEVICE(2, "教师设备");
        
        private final int code;
        private final String name;
        
        DeviceType(int code, String name) {
            this.code = code;
            this.name = name;
        }
        
        public int getCode() {
            return code;
        }
        
        public String getName() {
            return name;
        }
        
        @Override
        public String toString() {
            return name;
        }
        
        public static DeviceType fromCode(int code) {
            for (DeviceType type : values()) {
                if (type.getCode() == code) {
                    return type;
                }
            }
            return ALL_IN_ONE; // 默认返回一体机
        }
    }

    // 安全问题列表
    private final List<String> securityQuestions = Arrays.asList(
            "我喜欢的一个地方?",
            "我最喜欢的颜色?",
            "我的生日?",
            "我最喜欢的食物?"
    );

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 初始化安全问题下拉框
        securityQuestionCombo.setItems(FXCollections.observableArrayList(securityQuestions));
        securityQuestionCombo.getSelectionModel().selectFirst();
        
        // 初始化年级选择器
        SpinnerValueFactory<Integer> startValueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 12, 1);
        SpinnerValueFactory<Integer> endValueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 12, 6);
        startGradeSpinner.setValueFactory(startValueFactory);
        endGradeSpinner.setValueFactory(endValueFactory);
        
        // 初始化设备类型下拉框
        deviceTypeCombo.setItems(FXCollections.observableArrayList(DeviceType.values()));
        deviceTypeCombo.getSelectionModel().select(DeviceType.ALL_IN_ONE);
        
        // 添加设备类型选择监听器
        deviceTypeCombo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            updateUIBasedOnDeviceType(newValue);
        });
        
        // 初始化UI显示状态
        updateUIBasedOnDeviceType(DeviceType.ALL_IN_ONE);
        
        // 设置单位输入框焦点事件
        companyField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) { // 获得焦点
                if (companyField.getText().equals("(如: 郑州市金水区第二中学、郑州高新区文化活动中心)")) {
                    companyField.setText("");
                }
            } else { // 失去焦点
                if (companyField.getText().isEmpty()) {
                    companyField.setText("(如: 郑州市金水区第二中学、郑州高新区文化活动中心)");
                }
            }
        });
        
        // 设置状态标签初始状态
        statusLabel.setText("请填写注册信息，带*的为必填项");
        statusLabel.setStyle("-fx-text-fill: gray;");
    }

    /**
     * 设置注册管理器
     * @param registrationManager 注册管理器实例
     */
    public void setRegistrationManager(RegistrationManager registrationManager) {
        this.registrationManager = registrationManager;
    }

    /**
     * 设置主舞台
     * @param primaryStage 主舞台实例
     */
    public void setPrimaryStage(Stage primaryStage) {
        this.primaryStage = primaryStage;
    }

    /**
     * 处理取消按钮点击事件
     * @param event 事件对象
     */
    @FXML
    private void onCancelClicked(ActionEvent event) {
        // 显示确认对话框
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("取消注册");
        alert.setHeaderText("确认取消注册?");
        alert.setContentText("如果取消注册，系统将无法使用。确定要取消吗?");
        
        alert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                // 关闭对话框
                Stage stage = (Stage) cancelButton.getScene().getWindow();
                stage.close();
            }
        });
    }

    /**
     * 处理注册按钮点击事件
     * @param event 事件对象
     */
    @FXML
    private void onRegisterClicked(ActionEvent event) {
        // 获取输入的注册信息
        String registrationCode = registrationCodeField.getText().trim();
        String company = companyField.getText().trim();
        if (company.equals("(如: 郑州市金水区第二中学、郑州高新区文化活动中心)")) {
            company = "";
        }
        int startGrade = startGradeSpinner.getValue();
        int endGrade = endGradeSpinner.getValue();
        DeviceType deviceType = deviceTypeCombo.getValue();
        String email = emailField.getText().trim();
        String phone = phoneField.getText().trim();
        String securityQuestion = securityQuestionCombo.getValue();
        String securityAnswer = securityAnswerField.getText().trim();
        String confirmAnswer = confirmAnswerField.getText().trim();
        String teacherName = teacherNameField.getText().trim();
        
        // 验证注册码
        if (registrationCode.isEmpty()) {
            showError("请输入注册码");
            registrationCodeField.requestFocus();
            return;
        }

        
        // 验证单位名称
        if (company.isEmpty()) {
            showError("请输入单位名称");
            companyField.requestFocus();
            return;
        }
        
        // 验证设备类型
        if (deviceType == null) {
            showError("请选择设备类型");
            deviceTypeCombo.requestFocus();
            return;
        }
        
        // 根据设备类型进行相应验证
        if (deviceType == DeviceType.TEACHER_DEVICE) {
            // 验证教师名称
            //String teacherName = teacherNameField.getText().trim();
            if (teacherName.isEmpty()) {
                showError("请输入教师名称");
                teacherNameField.requestFocus();
                return;
            }
        } else {
            // 验证年级范围
            if (startGrade > endGrade) {
                showError("起始年级不能大于结束年级");
                startGradeSpinner.requestFocus();
                return;
            }
        }
        
        // 验证邮箱
        if (email.isEmpty()) {
            showError("请输入邮箱地址");
            emailField.requestFocus();
            return;
        }
        
        // 验证安全问题答案
        if (securityAnswer.isEmpty()) {
            showError("请输入安全问题答案");
            securityAnswerField.requestFocus();
            return;
        }
        
        // 验证确认答案
        if (confirmAnswer.isEmpty()) {
            showError("请确认安全问题答案");
            confirmAnswerField.requestFocus();
            return;
        }
        
        // 验证两次答案是否一致
        if (!securityAnswer.equals(confirmAnswer)) {
            showError("两次输入的安全问题答案不一致");
            confirmAnswerField.requestFocus();
            return;
        }
        
        // 显示注册中状态
        statusLabel.setText("正在连接服务器进行注册，请稍候...");
        statusLabel.setStyle("-fx-text-fill: blue;");
        registerButton.setDisable(true);
        
        // 构建额外信息（包含年级和设备类型）
        Map<String, String> extraInfo = new HashMap<>();
        extraInfo.put("startGrade", String.valueOf(startGrade));
        extraInfo.put("endGrade", String.valueOf(endGrade));
        
        // 获取设备类型的代码值
        Integer deviceTypeCode = deviceType != null ? deviceType.getCode() : null;
        
        // 执行注册
        try {
            String  remark =deviceTypeCode==2?teacherName:String.valueOf(startGrade)+"年级"+String.valueOf(endGrade)+"班";
            
            //获取设备系统信息
            Map<String, String> systemInfo = SystemInfoUtil.getSystemInfo();
            // 添加硬件ID
            systemInfo.put("hardwareId", SystemInfoUtil.getHardwareId());
            
            // 使用修改后的RegistrationManager的register方法，传递设备类型和系统信息
            boolean success = registrationManager.register(
                    registrationCode, company, email, phone, securityQuestion, securityAnswer, deviceTypeCode, systemInfo,remark);
            
            if (success) {
                // 注册成功
                String deviceId = registrationManager.getDeviceId();
                String successMsg = "注册成功！";
                if (deviceId != null && !deviceId.isEmpty()) {
                    successMsg += "\n设备ID: " + deviceId;
                }
                showSuccess(successMsg);
                
                // 关闭对话框
                Stage stage = (Stage) registerButton.getScene().getWindow();
                stage.close();
            } else {
                // 注册失败
                showError("注册失败，请检查注册信息是否正确");
                registerButton.setDisable(false);
            }
        } catch (Exception e) {
            // 注册异常
            showError("注册过程中发生错误: " + e.getMessage());
            registerButton.setDisable(false);
        }
    }

    /**
     * 显示错误信息
     * @param message 错误信息
     */
    private void showError(String message) {
        statusLabel.setText(message);
        statusLabel.setStyle("-fx-text-fill: red;");
    }

    /**
     * 显示成功信息
     * @param message 成功信息
     */
    private void showSuccess(String message) {
        statusLabel.setText(message);
        statusLabel.setStyle("-fx-text-fill: green;");
    }
    
    /**
     * 根据设备类型更新UI显示
     * @param deviceType 选择的设备类型
     */
    private void updateUIBasedOnDeviceType(DeviceType deviceType) {
        if (deviceType == DeviceType.TEACHER_DEVICE) {
            // 选择教师设备时，显示教师名称输入框，隐藏年级信息
            teacherLabel.setVisible(true);
            teacherLabel.setManaged(true);
            teacherNameField.setVisible(true);
            teacherNameField.setManaged(true);
            teacherRequiredLabel.setVisible(true);
            teacherRequiredLabel.setManaged(true);
            
            gradeLabel.setVisible(false);
            gradeLabel.setManaged(false);
            gradeBox.setVisible(false);
            gradeBox.setManaged(false);
        } else {
            // 选择一体机或机房设备时，显示年级信息，隐藏教师名称输入框
            gradeLabel.setVisible(true);
            gradeLabel.setManaged(true);
            gradeBox.setVisible(true);
            gradeBox.setManaged(true);
            
            teacherLabel.setVisible(false);
            teacherLabel.setManaged(false);
            teacherNameField.setVisible(false);
            teacherNameField.setManaged(false);
            teacherRequiredLabel.setVisible(false);
            teacherRequiredLabel.setManaged(false);
        }
    }
}